package seata.demo.order.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import seata.demo.common.dto.AccountDTO;
import seata.demo.common.dto.OrderDTO;
import seata.demo.common.enums.RspStatusEnum;
import seata.demo.common.feign.AccountServiceFeign;
import seata.demo.common.response.ObjectResponse;
import seata.demo.order.entity.TOrder;
import seata.demo.order.mappers.TOrderMapper;

import java.util.UUID;

/**
 * @description:
 * @author: dada
 * @date: 2020/11/24 16:46
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> {

    @Autowired
    private AccountServiceFeign accountServiceFeign;

    @PostMapping("/createOrder")
    @GlobalTransactional
    @Transactional
    public ObjectResponse<OrderDTO> createOrder(@RequestBody OrderDTO orderDTO) {

        log.info("seata全局xid={}", RootContext.getXID());

        ObjectResponse<OrderDTO> response = new ObjectResponse<>();
        //扣减用户账户
        AccountDTO accountDTO = new AccountDTO();
        accountDTO.setUserId(orderDTO.getUserId());
        accountDTO.setAmount(orderDTO.getOrderAmount());
        ObjectResponse objectResponse = accountServiceFeign.decreaseAccount(accountDTO);

        //生成订单号
        orderDTO.setOrderNo(UUID.randomUUID().toString().replace("-",""));
        //生成订单
        TOrder tOrder = new TOrder();
        BeanUtils.copyProperties(orderDTO,tOrder);
        tOrder.setCount(orderDTO.getOrderCount());
        tOrder.setAmount(orderDTO.getOrderAmount().doubleValue());
        try {
            baseMapper.createOrder(tOrder);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(RspStatusEnum.FAIL.getCode());
            response.setMessage(RspStatusEnum.FAIL.getMessage());
            return response;
        }

        if (objectResponse.getStatus() != 200) {
            response.setStatus(RspStatusEnum.FAIL.getCode());
            response.setMessage(RspStatusEnum.FAIL.getMessage());
            return response;
        }

        response.setStatus(RspStatusEnum.SUCCESS.getCode());
        response.setMessage(RspStatusEnum.SUCCESS.getMessage());
        return response;
    }

}
